<?php

namespace app\data\controller\shop;

use app\data\service\ExpressService;
use app\data\service\GoodsService;
use app\data\service\OrderService;
use app\data\service\PaymentService;
use app\data\service\PropertyService;
use app\data\service\UserAdminService;
use think\admin\Controller;
use think\admin\extend\CodeExtend;
use think\exception\HttpResponseException;

/**
 * 投资记录
 * Class Order
 * @package app\data\controller\shop
 */
class Order extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    private $table = 'ShopOrder';

    /**
     * 支付方式
     * @var array
     */
    protected $payments = [];

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        parent::initialize();
//        $this->payments = PaymentService::types();
    }

    /**
     * 投资记录管理
     * @auth true
     * @menu true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $this->title = '投资记录管理';

        $query = $this->_query($this->table);

        $expireStatus = input('expire_status');
        $where = [];

        if(($expireStatus !== null) && ($expireStatus !==  '')){
            if($expireStatus){
                $where[] = ['end_at', '<=', date('Y-m-d')];
            }else{
                $where[] = ['end_at', '>', date('Y-m-d')];
            }
        }

        $query->alias('so')
            ->leftJoin('shop_staff ss', 'ss.id=so.staff_id')
            ->equal('so.payment_method#payment_method,so.staff_id#staff_id')
            ->like('so.name#name,so.idcard#idcard,so.goods_name#goods_name')
            ->dateBetween('start_at#start_at')->dateBetween('end_at#end_at')
            ->where($where)
            ->field('so.*, ss.name as staff_name')
            ->order('so.id desc')->page();
    }

    /**
     * 投资列表处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$v){
            $v['expire_status'] = $v['end_at'] > date('Y-m-d') ? 0: 1;
        }
        $this->staff_list = $this->app->db->name('shop_staff')->where('deleted', '=', 0)->select();
    }

    /**
     * 添加投资记录
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        $this->mode = 'add';
        $this->title = '添加投资记录';
        $this->_form($this->table, 'form');
    }

    /**
     * 添加投资记录
     * @auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $this->mode = 'edit';
        $this->title = '修改投资记录';
        $this->_form($this->table, 'form');
    }

    /**@auth true
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function property(){
        $this->title = input('type') == 2 ? '解抵债权' : '匹配债权';
        $this->_form($this->table, 'form_property');
    }

    /**
    * 表单数据处理
    * @param array $data
    */
    protected function _property_form_filter(&$data)
    {
        if ($this->request->isPost()){

            switch (input('type')){
                case 1:
                    $order_id = input('id');
                    $property_id = input('property_id');
                    $match_cost = input('match_cost');

                    $res = PropertyService::instance()->saveProperty($order_id, $property_id, $match_cost);
                    if ($res > 0){
                        return $this->success('操作成功');
                    }else if ($res == -1){
                        return $this->error('当前债权可使用价值已不足');
                    }else if ($res == -2){
                        return $this->error('当前投资已使用该债权抵押，可删除后重新匹配');
                    }else if($res == -3){
                        return $this->error('债权额度已超出投资额度，请确认后重新再试');
                    }
                    return $this->success('操作成功');
                case 2:
                    $relation_id = input('id');

                    $res  = PropertyService::instance()->cancelProperty($relation_id);
                    break;
            }

            if ($res){
                return $this->success('操作成功');
            }else{
                return $this->success('操作失败');
            }
        }else{
            $orderProperty = PropertyService::instance()->getOrderProperty(['order_id' => $data['id']]);

            foreach ($orderProperty as $k => $item){

                $orderProperty[$k]['property_remain_cost'] = $item['property_cost'] - $item['property_match_cost'];
                $orderProperty[$k]['current_cost'] = $item['match_cost'];
            }

            $this->order_property = $orderProperty;

            $this->property_list = PropertyService::instance()->getPropertyList();
        }
    }


    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isGet()) {
            // 其他表单数据
            $this->goods_list = GoodsService::instance()->getGoods();
            $this->staff_list = $this->app->db->name('shop_staff')->where('deleted', '=', 0)->select();

            if(!empty($data)){
                foreach ($this->goods_list as $goods){
                    if($goods['id'] == $data['goods_id']){
                        $data['company_name'] = $goods['company_name'];
                        $data['cate_name'] = $goods['cate_name'];
                        break;
                    }
                }
            }
            if (!isset($data['id'])){
                $data['id'] = 0;
                $this->order_property = PropertyService::instance()->getOrderProperty($data['id']);
            }

        } elseif ($this->request->isPost()) {
            if(empty($data['id'])){
                if (empty($data['name'])) $this->error('客户名称不能为空');
                if (empty($data['staff_id'])) $this->error('业务员必选');
                if (empty($data['goods_id'])) $this->error('产品必选');
                if (empty($data['start_at'])) $this->error('起息日期必填');
                if (empty($data['start_at'])) $this->error('投资日期必填');
                if ($data['money'] <= 0) {
                    $this->error('投资金额必须大于0');
                }
                if ($data['payment_method'] < 0 ) {
                    $this->error('付款方式必选');
                }


                $goods = GoodsService::instance()->getInfo($data['goods_id']);

                $data['goods_time_type'] = $goods['time_type'];
                $data['goods_time_number'] = $goods['time_number'];
                $data['goods_name'] = $goods['name'];
                $data['goods_time_type'] = $goods['time_type'];
                $data['goods_annual_rate'] = $goods['annual_rate'];
                $data['goods_return_rule'] = $goods['return_rule'];
                $data['current_lxje']  = 0;

                switch ($data['goods_time_type']){

                    case 1://月
                        $months = $data['goods_time_number'];
                        break;
                    case 2://季度
                        $months = $data['goods_time_number']*3;
                        break;
                    case 3://年
                        $months = $data['goods_time_number']*12;
                        break;
                    default://天
                        $months = ceil($data['goods_time_number']/30);
                }
                $data['zhebiao'] = sprintf('%.2f', $months/12);
                $endDay = getEndDay($data['start_at'], $data['goods_time_number'],$data['goods_time_type']);
                $data['end_at'] = $endDay;
                $lxData = OrderService::instance()->calculateLx($data);
                $data = array_merge($data, $lxData);
                if($data['goods_return_rule'] == 2){
                    $flData = OrderService::instance()->calculateFl($data);
                    $data = array_merge($data, $flData);
                }


            }

        }
    }

    /**
     * 释放过期投资债权
     * @auth true
     */
    public function freed(){

        $now = date('Y-m-d');

        $expireIds = $this->app->db->name($this->table)->where('end_at', '<', $now)->column('id');

        foreach ($expireIds as $order_id){
            PropertyService::instance()->cancelAllByOrderId($order_id);
        }

        return $this->success('已完成释放');
    }

    /**
     * 状态修改
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function state()
    {
        $this->_save($this->table, $this->_vali([
            'status.in:0,1,2'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    public function item()
    {
        $this->title = '复利记录';

        $order_id = input('order_id');

        $query = $this->_query('shop_order_item');

        $where = [
            'order_id'  => $order_id
        ];

        $query->alias('oi')
            ->leftJoin('shop_order so', 'so.id=oi.order_id')
            ->where($where)
            ->field('oi.*, so.money')
            ->order('oi.id desc')->page();
    }

    /**@auth true
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function stopRate()
    {
        if ($this->request->isGet()) {
            $this->id = input('order_id');
            $item = OrderService::instance()->getInfo($this->id);
            $this->end_at = $item['end_at'];
            $this->goods_annual_rate = $item['goods_annual_rate'];
            $this->_form($this->table, 'form_stop_rate');
        } elseif ($this->request->isPost()) {
            $id = input('order_id');
            $item = OrderService::instance()->getInfo($id);
            $data['end_at'] = input('end_at');
            $data['goods_annual_rate'] = input('goods_annual_rate');
            $data['start_at']  = $item['start_at'];
            $data['money']  = $item['money'];
            $data['current_lxje']  = $item['current_lxje'];
            $data['id']  = $item['id'];

            $lxData = OrderService::instance()->calculateLx($data);
            $data = array_merge($data, $lxData);
            if($item['goods_return_rule'] == 2){
                $flData = OrderService::instance()->calculateFl($data);
                $data = array_merge($data, $flData);
            }else{
                OrderService::instance()->calculateLxLog($data);
            }
            if($item['current_lxje']){
                $temp['start_at'] = $data['start_at'];
                $temp['end_at'] = date('Y-m-01');
                $temp['goods_annual_rate'] = input('goods_annual_rate');
                $temp['money']  = $item['money'];

                $tempLxData = OrderService::instance()->calculateLx($temp);
                $data['lxce'] = $item['current_lxje']-$tempLxData['expect_lxje'];
            }
            $this->app->db->name('ShopOrder')
                ->where('id',$id)
                ->update($data);

            return $this->success('请求成功');

        }

    }

    /**
     * @param bool $state
     * @param array $data
     * @throws \think\db\exception\DbException
     */
    protected function _form_result(bool $state, array &$data)
    {
        if(empty($data['id']) && $data['goods_return_rule'] == 1){
            $id = $this->app->db->name('ShopOrder')->getLastInsID();
            $data['id'] = $id;
            OrderService::instance()->calculateLxLog($data);
        }
    }

    /**
     * 删除投资记录
     * @auth true
     * @throws \think\db\exception\DbException
     */
    public function remove()
    {

        $id = input('id');
        $property = PropertyService::instance()->getOrderProperty(['order_id'=>$id]);
        if($property){
            $this->error('解抵之后才能删除');
        }
        $this->app->db->name('ShopOrderItem')->where('order_id',$id)->delete();
        $this->app->db->name('ShopOrderReturnRateLog')->where('order_id',$id)->delete();
        $this->_delete($this->table);
    }
}